package com.blog.service.impl;

import com.blog.mapper.CommentMapper;
import com.blog.pojo.Comment;
import com.blog.pojo.CommentWithArticleTitleVO;
import com.blog.pojo.CommentWithUsernameAndImageVO;
import com.blog.pojo.PageBean;
import com.blog.service.CommentService;
import com.blog.utils.UserContext;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    // 分页查看所有评论
    @Override
    public PageBean listAll(Integer page, Integer pageSize) {
        // 设置分页参数
        PageHelper.startPage(page, pageSize);
        // 执行分页查询
        List<CommentWithArticleTitleVO> commentList = commentMapper.listAll();
        // 获取查询结果
        Page<CommentWithArticleTitleVO> p = (Page<CommentWithArticleTitleVO>) (commentList);
        // 封装PageBean
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
        return pageBean;
    }

    // 分页查看当前用户收到的所有评论
    @Override
    public PageBean listCurrentUser(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        int id = Integer.parseInt(UserContext.getUserId()); // 获取当前用户id
        List<CommentWithArticleTitleVO> commentList = commentMapper.listByUserId(id);
        Page<CommentWithArticleTitleVO> p = (Page<CommentWithArticleTitleVO>) (commentList);
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
        return pageBean;
    }

    // 查看一篇文章下所有评论
    @Override
    public List<CommentWithUsernameAndImageVO> listByArticleId(Integer id) {
        List<CommentWithUsernameAndImageVO>  commentList = commentMapper.listByArticleId(id);

        return commentList;
    }

    // 发布评论
    @Override
    public void add(Comment comment) {
        int userId = Integer.parseInt(UserContext.getUserId());
        comment.setUserId(userId);
        comment.setCreated(LocalDateTime.now());
        commentMapper.insert(comment);
    }

    // 根据id删除评论
    @Override
    public void deleteById(Integer id) {
        commentMapper.deleteById(id);
    }


}
